//
//  HomeMainController.m
//  AnimationRecommend
//
//  Created by ljm on 2017/2/15.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "HomeMainController.h"
#import "HomeMainCell.h"
#import "HomeMainModel.h"
#import "BeforeVC.h"

@interface HomeMainController ()<DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate>

@property (nonatomic, strong) NSMutableArray *newsList;

@end

@implementation HomeMainController

{
    NSInteger index ;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    index = 0;
    
    self.tableView.scrollsToTop = NO;
//    self.view.backgroundColor = RGBCOLOR(239, 239, 239);
    self.view.backgroundColor = [UIColor whiteColor];
//    self.tableView.backgroundColor = iCodeTableviewBgColor;
    self.tableView.rowHeight = 90.f;
    [self loadDataSource];
}

#pragma mark -- 网络请求
- (void) loadDataSource
{
    __weak typeof(self) weakSelf = self;

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        
        NSString *urlPage = [NSString stringWithFormat:@"%ld",index];
        NSString *urlPull = [NSString stringWithFormat:@"%@%@",MainPageUrlStr,urlPage];
        
        [[NetworkTools shareTools] requestWithMethod:POST andURL:urlPull andParameters:nil andCallBack:^(id data, NSError *error) {
            if (!error) {
                /*
                 *    使用模型赋值
                 */
                NSArray *posts = data[@"posts"];
                _newsList = [NSMutableArray new];
                _newsList = [HomeMainModel mj_objectArrayWithKeyValuesArray:posts];
                
                [weakSelf.tableView reloadData];
                //请求成功，停止刷新
                [weakSelf.tableView.mj_header endRefreshing];
                
                
            }else {
                NSLog(@"-------------error-----------------\n%@",error);
                /*
                 *    请求失败
                 */
                [weakSelf.tableView.mj_header endRefreshing];
            }
        }];
        
//        [[NetworkTools shareTools]  POST:urlPull parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            //成功
////            NSLog(@"%@",responseObject);
//            
//            //使用模型赋值
//            NSArray *posts = responseObject[@"posts"];
//            _newsList = [NSMutableArray new];
//            _newsList = [HomeMainModel mj_objectArrayWithKeyValuesArray:posts];
//            
////            for (HomeMainModel *iv in _newsList) {
////                NSLog(@"============%@=============",iv.title);
////            }
//            
//            [weakSelf.tableView reloadData];
//            //请求成功，停止刷新
//            [weakSelf.tableView.mj_header endRefreshing];
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            //失败
//            NSLog(@"网络请求失败======================\n%@",error);
//            
//            //请求失败，停止刷新
//            [weakSelf.tableView.mj_header endRefreshing];
//        }];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        index+= 1;
        NSString *urlStr = [NSString stringWithFormat:@"%ld",index];
        NSString *urlPush = [NSString stringWithFormat:@"%@%@",MainPageUrlStr,urlStr];
        
        dispatch_queue_t queue = dispatch_get_main_queue() ;
        dispatch_async(queue, ^{
            
            [[NetworkTools shareTools] requestWithMethod:POST andURL:urlPush andParameters:nil andCallBack:^(id data, NSError *error) {
                if (!error) {
                    //成功
                    NSArray *posts = data[@"posts"];
                    NSArray *resposeArr = [HomeMainModel mj_objectArrayWithKeyValuesArray:posts];
                    for (HomeMainModel *model in resposeArr) {
                        [weakSelf.newsList addObject:model];
                    }
                    
                    if (resposeArr.count == 0) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            weakSelf.tableView.mj_footer.hidden = YES;
                        });
                    }
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
                else
                {
                    //失败
                    NSLog(@"----------------------%@",error);
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }];
            
//            [[NetworkTools shareTools] POST:urlPush parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                //成功
//                NSArray *posts = responseObject[@"posts"];
//                NSArray *resposeArr = [HomeMainModel mj_objectArrayWithKeyValuesArray:posts];
//                for (HomeMainModel *model in resposeArr) {
//                    [weakSelf.newsList addObject:model];
//                }
//                
//                if (resposeArr.count == 0) {
//                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        weakSelf.tableView.mj_footer.hidden = YES;
//                    });
//                }
//                [weakSelf.tableView reloadData];
//                [weakSelf.tableView.mj_footer endRefreshing];
//                
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                //失败
//                NSLog(@"----------------------%@",error);
//                [weakSelf.tableView.mj_footer endRefreshing];
//            }];
        });
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    VTPRINT_METHOD
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.tableView.scrollsToTop = YES;
    VTPRINT_METHOD
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.tableView.scrollsToTop = NO;
    VTPRINT_METHOD
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    VTPRINT_METHOD
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _newsList.count;
}

#pragma mark -- 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeMainCell *cell = nil;
    static NSString *cellID = @"cell.Identifier";
    cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[HomeMainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
//    NSString *imageName = [NSString stringWithFormat:@"image_%ld", (long)indexPath.row%13];
//    [cell.iconView setImage:[UIImage imageNamed:imageName]];
//    
//    if (indexPath.row == 0) {
//        cell.titleLabel.text = @"今日";
//    }else {
//        cell.titleLabel.text = [NSString stringWithFormat:@"%ld天前",indexPath.row ];
//    }
//    cell.descLabel.text = @"http://v.youku.com/v_show/id_XNzA2Nzc3MDg=.html?&f=2969173&from=y1.2-3.4.3&spm=a2h0j.8191423.item_XNzA2Nzc3MDg=.A";
    
    HomeMainModel *model = _newsList[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark -- 点击cell，action
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeMainModel *model = _newsList[indexPath.row];
    BeforeVC *bvc = [[BeforeVC alloc]init];
    bvc.title = @"详情";
    bvc.url = model.url;
    NSLog(@"%@",bvc.url);
    [self.navigationController pushViewController:bvc animated:YES];
}

#pragma mark - VTMagicReuseProtocol
- (void)vtm_prepareForReuse
{
    // reset content offset
    NSLog(@"clear old data if needed:%@", self);
    [self.tableView setContentOffset:CGPointZero];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
